package com.atguigu.springcloud.lb.impl;

import com.atguigu.springcloud.lb.LoadBalancer;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @program: cloud2020
 * @description: 轮询算法原则:rest接口请求数 % 服务器的集群总数 = 实例调用服务器的位置下标. 并且每次服务器重启后,接口请求数重置为1
 * @author: YuWenYi
 * @create: 2021-04-14 19:51
 **/
@Component
public class LoadBalancerImpl implements LoadBalancer {

    AtomicInteger atomicInteger = new AtomicInteger(0);

    //获取服务器的访问次数,并写入atomicInteger中
    public final int getAndIncrement(){
        int current;
        int next;
        //使用自旋锁!
        do {
            current = this.atomicInteger.get();
            next = current >= Integer.MAX_VALUE ? 0 : current+1;
        }while (!this.atomicInteger.compareAndSet(current,next));
        System.out.println("第几次访问数--->next为:"+next);
        return next;
    }

    @Override
    public ServiceInstance instances(List<ServiceInstance> serviceInstances) {
        //获取服务器下标
        int index = getAndIncrement() % serviceInstances.size();

        return serviceInstances.get(index);
    }
}
